package com.cgbl.cg.ui.mine

import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.cgbl.cg.BR
import com.cgbl.cg.R
import com.cgbl.cg.adapter.ProjectAdapter
import com.cgbl.cg.databinding.AppActivityProjectCenterBinding
import com.cgbl.cg.vm.mine.ProjectCenterViewModel
import com.robot.base.base.activity.GLBaseActivity
import com.robot.base.configs.AppConstants
import com.robot.base.model.CustomerItemInfo
import com.robot.base.util.arouter.ARouterUtil

@Route(path = AppConstants.Router.Mine.A_MINE_PROJECT_CENTER)
class ProjectCenterActivity :
    GLBaseActivity<AppActivityProjectCenterBinding, ProjectCenterViewModel>() {

    lateinit var projectAdapter: ProjectAdapter

    override fun initComponents() {
        initTiterBar()
        initView()
    }

    override fun initData() {
        super.initData()
        viewModel.refresh()
    }
    private fun initTiterBar() {
        val titleView = findViewById<TextView>(R.id.tv_title)
        val backView = findViewById<ImageView>(R.id.iv_back)
        titleView.text = "项目中心"
        backView.setOnClickListener { finish() }
    }

    private fun initView() {
        projectAdapter = ProjectAdapter()
        binding.recyclerView.apply {
            layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
            adapter = projectAdapter
        }

        projectAdapter.setOnItemClickListener { adapter, view, position ->
            ARouterUtil.goToActivityWithBundle(AppConstants.Router.PROJECT.A_MY_PROJECT_DETAIL,
                Bundle().apply {
                    putString(AppConstants.BundleKey.ID, projectAdapter.data[position].id)
                })
        }
    }

    override fun initContentView(savedInstanceState: Bundle?): Int =
        R.layout.app_activity_project_center

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewObservable() {
        super.initViewObservable()
        binding.smartRefreshLayout.setOnRefreshListener {
            viewModel.refresh()
        }
        binding.smartRefreshLayout.setOnLoadMoreListener {
            viewModel.load()
        }

        viewModel.uc.refreshEvent.observe(this) {
            binding.smartRefreshLayout.finishLoadMore()
            binding.smartRefreshLayout.finishRefresh()
        }

        viewModel.uc.dataEvent.observe(this) {
            if (viewModel.pageNo == 1) {
                projectAdapter.setNewInstance(it as MutableList<CustomerItemInfo>?)
            } else {
                projectAdapter.addData(it)
            }
        }
    }
}